package com.daisuxia.back.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daisuxia.back.dao.IAuditCenterDao;
import com.daisuxia.back.dao.ICreditLoanPayDao;
import com.daisuxia.back.dao.IMmanLoanCollectionOrderDao;
import com.daisuxia.back.dao.IMmanUserLoanDao;
import com.daisuxia.back.dao.IPaginationDao;
import com.daisuxia.back.result.JsonResult;
import com.daisuxia.back.utils.IdGen;
import com.daisuxia.config.PayContents;
import com.daisuxia.constant.Constant;
import com.daisuxia.web.pojo.AuditCenter;
import com.daisuxia.web.pojo.CreditLoanPay;
import com.daisuxia.web.pojo.MmanLoanCollectionOrder;
import com.daisuxia.web.pojo.MmanUserLoan;
import com.daisuxia.web.util.HttpUtil;
import com.daisuxia.web.util.PageConfig;
import com.daisuxia.web.util.encrypt.AESUtil;
import com.daisuxia.web.util.encrypt.MD5coding;

import net.sf.json.JSONObject;

@Service
public class AuditCenterService implements IAuditCenterService {
    private static Logger logger = LoggerFactory.getLogger(AuditCenterService.class);
    @Autowired
    private IAuditCenterDao auditCenterDao;
    @Autowired
    private IPaginationDao paginationDao;
    @Autowired
	private IMmanLoanCollectionOrderDao mmanLoanCollectionOrderDao;
	@Autowired
	private IMmanUserLoanDao manUserLoanDao;
    //订单
    @Autowired
    private IMmanLoanCollectionOrderDao manLoanCollectionOrderDao;
    @Autowired
    private IMman_loan_collection_orderdeductionService collection_orderdeductionService;
    @Autowired
    private IMmanUserLoanService iMmanUserLoanService;
    @Autowired
    private IMmanUserLoanDao iMmanUserLoanDao;
    @Autowired
    private ICreditLoanPayDao iCreditLoanPayDao;
    @Override
    public JsonResult svueAuditCenter(Map<String, String> params) {
        JsonResult result = new JsonResult("-1", "操作失败");
        MmanLoanCollectionOrder mmanLoanCollectionOrderOri = manLoanCollectionOrderDao.getOrderById(params.get("id"));
        AuditCenter auditCenter = new AuditCenter();
        if (StringUtils.isNotBlank(params.get("id"))) {
            auditCenter.setOrderid(mmanLoanCollectionOrderOri.getId());
            auditCenter.setLoanUserId(mmanLoanCollectionOrderOri.getUserId());

        }
        auditCenter.setId(IdGen.uuid());
        auditCenter.setCreatetime(new Date());
        auditCenter.setNote(params.get("note"));
        auditCenter.setType(params.get("type"));
        auditCenter.setOperationUserId(params.get("operationUserId"));
        auditCenter.setRemark(params.get("remark"));
        auditCenter.setStatus("0");
        int cont = auditCenterDao.saveUpdate(auditCenter);
        if (cont > 0) {
//			HashMap<String, Object> xjxparams =new HashMap<String, Object>();
//			params.put("id",auditCenter.getLoanUserId());
//			params.put("collection_advise", auditCenter.getNote());
//			String collectionAdviseUpdateResult = HttpUtil.dopostMap(PayContents.COLLECTION_ADVISE_UPDATE_URL, params);
            result.setMsg("操作成功");
            result.setCode("0");
        }
        return result;
    }
    
    
    @Override
    public PageConfig<AuditCenter> findPage(HashMap<String, Object> params) {
        params.put(Constant.NAME_SPACE, "AuditCenter");
        PageConfig<AuditCenter> pageConfig = new PageConfig<AuditCenter>();
        pageConfig = paginationDao.findPage("findAll", "findAllCount", params, null);
        return pageConfig;
    }

    @Override
    public JsonResult updateAuditCenter(Map<String, String> params) {
        JsonResult result = new JsonResult("-1", "审核失败");

        String ids = params.get("id");
        String[] orderIds = ids.split(",");

        if (orderIds.length > 20) {
            result.setMsg("请选择信息不要超过20条");
        } else {
            int jxlCount = 0;
            int csjyCount = 0;
            int jmCount = 0;
            boolean markStatus = true; // 申请中状态
            for (String orderId : orderIds) {
                AuditCenter auditCenter = auditCenterDao.findAuditId(orderId);
                if (auditCenter != null) {
                    if ("1".equals(auditCenter.getType())) { //聚信立
                        jxlCount++;
                    } else if ("2".equals(auditCenter.getType())) { //催收建议
                        csjyCount++;
                    } else if ("3".equals(auditCenter.getType())) {//订单减免
                        jmCount++;
                    }

                    if (!"0".equals(auditCenter.getStatus()) && markStatus) {
                        markStatus = false; // 非申请中状态
                    }
                }
            }
            logger.error("updateAuditCenter jxlCount=" + jxlCount + " orderIds=" + orderIds.length + " csjyCount=" + csjyCount + " markStatus=" + markStatus + " id=" + params.get("id"));
            if (jxlCount == orderIds.length || csjyCount == orderIds.length || jmCount == orderIds.length) {
                if (markStatus) {
                    if (StringUtils.isNotBlank(params.get("id"))) {
                        int successCount = 0;
                        for (String orderId : orderIds) {
                            successCount = updateAuditStatus(params, result, successCount, orderId);
                        }
                        if (successCount == orderIds.length) {
                            result.setMsg("审核成功");
                            result.setCode("0");
                        } else {
                            result.setMsg("总单:" + orderIds.length + "，审核成功：" + successCount);
                        }
                        params.put("id", ids);
                    } else {
                        result.setMsg("请选择需要审核的信息");
                    }
                } else {
                    result.setMsg("申请中的状态才能去审核");
                }
            } else {
                result.setMsg("请选择审核类型相同的信息");
            }
        }
        return result;
    }

    private int updateAuditStatus(Map<String, String> params, JsonResult result, int successCount, String orderId) {
        BigDecimal bigDecimal = new BigDecimal(0);
        logger.error("updateAuditCenter id=" + params.get("id") + " status=" + params.get("status") + " orderId=" + orderId);
        if (StringUtils.isNotBlank(params.get("id")) && StringUtils.isNotBlank(params.get("status"))) {
                AuditCenter auditCenter = auditCenterDao.findAuditId(orderId);
            if (auditCenter != null) {
                auditCenter.setStatus(params.get("status"));
                params.put("id", orderId);
                auditCenterDao.updateStatus(params);
                HashMap<String, String> auditMap = new HashMap<String, String>();
                auditMap.put("id", auditCenter.getOrderid());
                if ("2".equals(auditCenter.getType())) {
                    auditMap.put("csstatus", params.get("status"));
                    manLoanCollectionOrderDao.updateAuditStatus(auditMap);
                    if ("2".equals(auditCenter.getStatus())) {
                        HashMap<String, Object> xjxparams = new HashMap<String, Object>();
                        params.put("id", auditCenter.getLoanUserId());
                        params.put("collection_advise", auditCenter.getNote());
                        String resultT = HttpUtil.dopostMap(PayContents.COLLECTION_ADVISE_UPDATE_URL, params);
                        logger.error("updateAuditStatus COLLECTION_ADVISE_UPDATE_URL=" + PayContents.COLLECTION_ADVISE_UPDATE_URL + " params=" + params.toString() + " resultT=" + resultT);
                    }

                } else if ("1".equals(auditCenter.getType())) {
                    auditMap.put("jxlStatus", params.get("status"));
                    manLoanCollectionOrderDao.updateAuditStatus(auditMap);
                 //特殊原因
                } else if ("3".equals(auditCenter.getType()) && ("2".equals(auditCenter.getStatus()) || "5".equals(auditCenter.getStatus()))){
                    auditMap.put("status", params.get("status"));
                    MmanUserLoan loan = iMmanUserLoanDao.get(auditCenter.getLoanId());
                    CreditLoanPay loanPay= iCreditLoanPayDao.get(auditCenter.getPayId());
                    int reductionMoney= Integer.parseInt( String.valueOf(auditCenter.getReductionMoney()));//减免滞纳金
                    int ReceivableMoney=loanPay.getReceivableMoney().intValue();//应还金额
                    int realMoney=loanPay.getRealMoney().intValue();//实收金额
                    if(realMoney < ReceivableMoney){
                    	if( reductionMoney >ReceivableMoney-realMoney ) 
                    		reductionMoney=ReceivableMoney-realMoney;
                        logger.error("reductionMoney =" +reductionMoney);
                        String sign = MD5coding.MD5(AESUtil.encrypt(auditCenter.getLoanUserId()+auditCenter.getPayId()+reductionMoney*100+auditCenter.getId(),PayContents.XJX_WITHHOLDING_NOTIFY_KEY));
                        logger.error("reductionMoney =" +reductionMoney*100);
                        //2、发起请求
                        String withholdPostUrl=PayContents.XJX_JIANMIAN_URL+"/"+auditCenter.getLoanUserId()+"/"+auditCenter.getPayId()+"/"+reductionMoney*100+"/"+auditCenter.getId()+"/"+sign;
                        logger.error("减免请求地址："+withholdPostUrl);
                        String xjxWithholdingStr = HttpUtil.getHttpMess(withholdPostUrl, "", "POST", "UTF-8");
                        if(StringUtils.isNotBlank(xjxWithholdingStr)) {
                            JSONObject jos = new JSONObject().fromObject(xjxWithholdingStr);
                            logger.info("返回还款结果信息jos转换"+jos);
                            if ("-100".equals(jos.get("code"))) {
                                logger.error("-100","系统错误");
                            }else if("0".equals(jos.get("code"))){
                            	logger.error("0","减免成功！");
                            	//用户发送短信
                                String msg= auditCenter.getLoanUserName()+"，您的减免已生效，请您在今日23点之前还款"+bigDecimal+"元，逾期未还将不予减免。请您联系催收员进行代扣，或通过支付宝还款并备注您的姓名和电话";
                                System.out.println("msg "+msg);
                                if (auditCenter.getLoanUserPhone()!=null){
                                	//SMS253Util.sendSmsDiyCL(auditCenter.getLoanUserPhone(), msg);
                                }
                                if("2".equals(auditMap.get("status"))){
                                    auditMap.put("status","7");
                                    manLoanCollectionOrderDao.sveUpdateJmStatus(auditMap);
                                    HashMap<String, Object> map = new HashMap<String, Object>();
                                    map.put("orderId",auditCenter.getOrderid());
                                    map.put("reductionMoney",auditCenter.getReductionMoney());
                                    manLoanCollectionOrderDao.updateReductionMoney(map);
                                }
                                if("5".equals(auditCenter.getStatus())){
                                    auditMap.put("status","7");
                                    manLoanCollectionOrderDao.sveUpdateJmStatus(auditMap);
                                    HashMap<String, Object> aumap = new HashMap<String, Object>();
                                    aumap.put("orderId",auditCenter.getOrderid());
                                    aumap.put("reductionMoney",0);
                                    manLoanCollectionOrderDao.updateReductionMoney(aumap);
                                }
                            }else if("-101".equals(jos.get("code"))){
                                logger.error("-101","参数错误 减免失败！！！");
                            }
                        }
                    }else {
                    	//无效申请
                    	auditMap.put("status","4");
                        manLoanCollectionOrderDao.sveUpdateJmStatus(auditMap);
                        result.setMsg("申请不合法,已失效！");
                    }
                } else if ("3".equals(auditCenter.getType()) && "3".equals(auditCenter.getStatus())) {
                    auditMap.put("status", params.get("status"));
                    if("3".equals(auditMap.get("status"))){
                        auditMap.put("status","8");
                    }
                    manLoanCollectionOrderDao.sveUpdateJmStatus(auditMap);
                }
                successCount++;
            } else {
                result.setMsg("改信息不存在");
            }
        } else {
            result.setMsg("审核参数错误");
        }
        return successCount;
    }

    /**
     * 减免审核
     */
    @Override
    public JsonResult saveorderdeduction(Map<String, Object> params) throws ParseException {
        JsonResult result = new JsonResult("-1", "申请减免失败！");
        MmanLoanCollectionOrder collectionOrder = manLoanCollectionOrderDao.getOrderById(params.get("id").toString());
        String deductionMoney = (String) params.get("deductionmoney");
        int money  =Integer.valueOf(deductionMoney);
        if(money!=0){// 金额校验
            if (collectionOrder != null) {
                //更新订单状态
                collectionOrder.setStatus((String) params.get("note"));
                System.out.println("hvdjksfj" + params.get("note"));
                manLoanCollectionOrderDao.updateJmStatus(collectionOrder);
                AuditCenter auditCenter = new AuditCenter();
                //添加减免审核
                if (StringUtils.isNotBlank((String) params.get("id"))) {
                    auditCenter.setOrderid(collectionOrder.getId());
                    auditCenter.setLoanUserId(collectionOrder.getUserId());
                }
                auditCenter.setId(IdGen.uuid());
                auditCenter.setCreatetime(new Date());
                auditCenter.setNote((String) params.get("note"));
                auditCenter.setType((String) params.get("type"));
                auditCenter.setOperationUserId((String) params.get("operationUserId"));
                auditCenter.setRemark((String) params.get("deductionremark"));
                auditCenter.setReductionMoney(new Long(deductionMoney));
                auditCenter.setLoanPenalty(new BigDecimal(String.valueOf(params.get("loanPenlty"))));
                auditCenter.setLoanId((String) params.get("loanId"));
                auditCenter.setPayId((String) params.get("payId"));
                auditCenter.setLoanUserName((String) params.get("name"));
                auditCenter.setLoanUserPhone((String) params.get("phone"));
                auditCenter.setOrderStatus((String) params.get("orderStatus"));
                int cont = auditCenterDao.saveNotNull(auditCenter);
                if (cont > 0) {
                    result.setMsg("申请成功！等待审核");
                    result.setCode("0");
                }
            }
        }else {
            result.setMsg("减免金额不能小于等于0");
        }
        return result;

    }
    @Override
    public PageConfig<AuditCenter> findAllPage(HashMap<String, Object> params) {
        params.put(Constant.NAME_SPACE, "AuditCenter");
        PageConfig<AuditCenter> pageConfig = new PageConfig<AuditCenter>();
        pageConfig = paginationDao.findPage("find", "findCount", params, null);
        return pageConfig;
    }
    @Override
    public void updateSysStatus(Map<String, String> params) {
        auditCenterDao.updateSysStatus(params);
    }
    
	@Override
	public JsonResult saveSuggestionApply(Map<String, String> params) throws ParseException {
		JsonResult result=new JsonResult("-1","添加失败");
		String orderId = params.get("id");
		MmanLoanCollectionOrder mmanLoanCollectionOrder = mmanLoanCollectionOrderDao.getOrderById(orderId);
		if(!"3".equals(params.get("status"))&&(StringUtils.isEmpty(mmanLoanCollectionOrder.getCsstatus())||Constant.CS_STATUS_REFUSE==mmanLoanCollectionOrder.getCsstatus())) {
			MmanUserLoan manUserLoan = manUserLoanDao.get(mmanLoanCollectionOrder.getLoanId());
			AuditCenter audit = new AuditCenter();
			audit.setId(IdGen.uuid());
			audit.setType("2");//风控建议申请
			audit.setOrderid(params.get("id"));
			audit.setOperationUserId(params.get("backUserId"));
			audit.setLoanUserId(mmanLoanCollectionOrder.getUserId());
			audit.setLoanId(mmanLoanCollectionOrder.getLoanId());
			audit.setPayId(mmanLoanCollectionOrder.getPayId());
			audit.setStatus("0");
			audit.setCreatetime(new Date());
			audit.setNote(params.get("status"));
			audit.setLabelValue(params.get("fkLabels"));
			audit.setRemark(params.get("fkLabels"));
			audit.setLoanPenalty(manUserLoan.getLoanPenalty());
			audit.setLoanUserName(mmanLoanCollectionOrder.getLoanUserName());
			audit.setLoanUserPhone(mmanLoanCollectionOrder.getLoanUserPhone());
			if(auditCenterDao.saveNotNull(audit)>0) {
				mmanLoanCollectionOrder.setCsstatus(Constant.CS_STATUS_APPLY);
				mmanLoanCollectionOrder.setOperatorName(params.get("userName"));
				mmanLoanCollectionOrder.setUpdateDate(new Date());
				mmanLoanCollectionOrderDao.updateCollectionOrder(mmanLoanCollectionOrder);
				result.setCode("0");
				result.setMsg("添加成功");
			}
		}
		return result;
	}

    
    
   /**
     * 减免推真实测试地址
     */
   public  static void   HttpPost(){
        String user_id="438780";
        String pay_id="63861";
        int money= 35000;
        String  uuid ="734aa7a95b39403ca0242adcf56e4d82";
        String sign = MD5coding.MD5(AESUtil.encrypt(user_id + pay_id + money + uuid, PayContents.XJX_WITHHOLDING_NOTIFY_KEY));
        //2、发起请求
        String withholdPostUrl=PayContents.XJX_JIANMIAN_URL+"/"+ user_id +"/"+ pay_id +"/"+ money +"/"+ uuid +"/"+sign;
        logger.error("减免请求地址："+withholdPostUrl);
        String xjxWithholdingStr = HttpUtil.getHttpMess(withholdPostUrl, "", "POST", "UTF-8");
        JSONObject jos = new JSONObject().fromObject(xjxWithholdingStr);
        System.out.println(jos);
    }

    public static void main(String[] args) {
        HttpPost();
    }


}
